var generationDiv = document.getElementById('gen-div')
function updateGenerationDiv(generation) {
  GLOBAL_CONFIG.generation = generation
  generationDiv.innerHTML = `代数：${generation}`
}

function getPatternCells(pattern, x, y) {
  if (pattern == null) return
  console.log('getPatternCells')
  var cells = []
  pattern.structure.forEach(function(offset) {
    var nx = x + offset[0]
    var ny = y + offset[1]
    nx = (nx + gridWidth) % gridWidth
    ny = (ny + gridHeight) % gridHeight
    cells.push(GLOBAL_CONFIG.cells[ny][nx])
  })
  return cells
}

function clearGhosts() {
  GLOBAL_CONFIG.cells.forEach(function(row) {
    row.forEach(function(cell) {
      cell.classList.remove('ghost')
    })
  })
}

function drawPattern(cells, type) {
  clearGhosts()
  cells.forEach(function(cell) {
    if (cell.classList.contains('alive')) {
      return
    }
    cell.classList.add(type)
  })
}

function nextGeneration() {
  var changes = []
  for (var y = 0; y < gridHeight; y++) {
    for (var x = 0; x < gridWidth; x++) {
      var aliveNeighbors = 0
      for (var dy = -1; dy <= 1; dy++) {
        for (var dx = -1; dx <= 1; dx++) {
          if (dx == 0 && dy == 0) continue
          var ny = y + dy
          var nx = x + dx
          ny = (ny + gridHeight) % gridHeight
          nx = (nx + gridWidth) % gridWidth
          if (GLOBAL_CONFIG.cells[ny][nx].classList.contains('alive')) {
            aliveNeighbors++
          }
        }
      }
      var cell = GLOBAL_CONFIG.cells[y][x]
      var isAlive = cell.classList.contains('alive')
      if (isAlive) {
        if (aliveNeighbors < 2 || aliveNeighbors > 3) {
          changes.push({ cell: cell, state: 'dead' })
        }
      } else {
        if (aliveNeighbors == 3) {
          changes.push({ cell: cell, state: 'alive' })
        }
      }
    }
  }
  // 应用变化
  changes.forEach(function(change) {
    if (change.state == 'alive') {
      change.cell.classList.add('alive')
    } else {
      change.cell.classList.remove('alive')
    }
  })
  updateGenerationDiv(GLOBAL_CONFIG.generation + 1)
}
